package mf.trees.all;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * GUI-Window for tree navigation.
 * 
 * @author Maik Funkat
 */
public class TreeFrame extends JFrame implements KeyListener {

	private static final long serialVersionUID = 8546266203494771896L;
	private static final String LABEL_TEXT = "<html><body>"+
			"Start is the root node of the tree. Navigate with number i to the i-th child of "+
			"the current node. Navigate with the up arrow to the father node."+
			"</body></html>";
	
	TreeModel data;
	
	//information label
	JLabel lblInfo = new JLabel(LABEL_TEXT);
	//debug label
	JLabel lblDebug = new JLabel("<html><body></body></html>");
	
	//here the output is presented
	JTextArea taOutput = new JTextArea();
	
	//scroll pane for longer texts
	JScrollPane spOutput;
	
	/** Constructs a new TreeFrame with title <i>title</i> and tree model <i>model</i>. */
	public TreeFrame(String title, TreeModel model) {
		//set model
		data = model;

		//some general settings
		setTitle(title);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(640, 155 + (data.debugMode() ? 40 : 0));
		setResizable(false);
		setLayout(null);
		
		//add key Listener 
		addKeyListener(this);
		
		//set info labels
		lblInfo.setLocation(0, 0);
		lblInfo.setSize(600, 40);
		
		//set debug labels
		lblDebug.setLocation(0, 125);
		lblDebug.setSize(640, 40);
		lblDebug.setText(data.getDebugText());

		//set output text area
		taOutput.setLineWrap(true);
		taOutput.setEnabled(false);
		taOutput.setBackground(new Color(238, 238, 238));
		taOutput.setDisabledTextColor(Color.BLACK);
		taOutput.setText(data.getNodeLabel());
		taOutput.setAutoscrolls(false);

		//add scroll pane
		spOutput = new JScrollPane(
				JScrollPane.VERTICAL_SCROLLBAR_NEVER,
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		spOutput.setViewportView(taOutput);
		spOutput.setSize(getWidth() - 6, 85);
		spOutput.setLocation(0, 40);
		
		//put all together
		add(lblInfo);
		add(lblDebug);
		add(spOutput);
	}

	/** Handle pressed keys. */
	public void keyPressed(KeyEvent e) {
		switch (e.getKeyCode()) {
		default:
			return;
		case KeyEvent.VK_1:
		case KeyEvent.VK_2:
		case KeyEvent.VK_3:
		case KeyEvent.VK_4:
		case KeyEvent.VK_5:
		case KeyEvent.VK_6:
		case KeyEvent.VK_7:
		case KeyEvent.VK_8:
		case KeyEvent.VK_9:
			data.gotoSon(e.getKeyCode()-49);
			break;
		case KeyEvent.VK_UP:
			data.gotoFatherNode();
			break;
		case KeyEvent.VK_R:
			data.resetStack();
			break;
		}
		
		lblDebug.setText(data.getDebugText());
		taOutput.setText(data.getNodeLabel());
	}

	public void keyReleased(KeyEvent arg0) {}
	public void keyTyped(KeyEvent arg0) {}
}
